package com.gjt.thread.Thread;

import com.gjt.thread.entity.InstanceCallDigest;

import java.io.FileInputStream;
import java.io.IOException;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created with Intel IDEA.
 * 使用实例方法进行回调线程的返回值
 *
 * @Auther: gjt
 * @Date: 2024/3/20 20:18
 */
public class InstanceDigestRunnable implements Runnable{
    private String fileName;

    // 回调实列
    private InstanceCallDigest callback;

    // 把实例传入
    public InstanceDigestRunnable(String fileName, InstanceCallDigest callback) {
        this.fileName = fileName;
        this.callback = callback;
    }

    @Override
    public void run() {
        try(FileInputStream in=new FileInputStream(fileName)){
            // 计算一个256位的SHA-2消息摘要 用到的DigestInputStream
            MessageDigest sha = MessageDigest.getInstance("SHA-256");
            DigestInputStream din = new DigestInputStream(in, sha);

            while(din.read() != -1);//读取到最后并计算摘要
            din.close();

            // 获取摘要
            byte[] digest = sha.digest();

            // 调用实列的方法 把实例中digest 赋值
            callback.receiveDigest(digest);
        }catch (IOException e){
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }
}
